import api from '../../../utils/api'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: ["待领取", "已领取"],
    activeIndex: 0,
    hasMore: true,
    pageNo: 1,
    list: [],
    couWidth:'85%',
    dlq:true,
    // 触摸开始时间
    touchStartTime: 0,
    // 触摸结束时间
    touchEndTime: 0,
    // 最后一次单击事件点击发生时间
    lastTapTime: 0,
    // 单击事件点击后要触发的函数
    lastTapTimeoutFunc: null,
  },

  //按钮触摸开始触发的事件
  touchStart: function (e) {
    this.touchStartTime = e.timeStamp
  },

  //按钮触摸结束触发的事件
  touchEnd: function (e) {
    this.touchEndTime = e.timeStamp
  },

  

  //获取卡券列表 
  _get_couponlist(idx){
    if(idx == 1){
      this._load_received()
    }else{
      this._load_unclaimed()
    }
  },

  // 封装遍历数据的函数
  _for_data(data,list){
    if (data.length) {
      for (var i = 0; i < data.length; i++) {
        let date_type = data[i].date_type;
        let fixed_begin_term = data[i].fixed_begin_term
        let begin_timestamp = data[i].begin_timestamp;
        let end_timestamp = data[i].end_timestamp;
        let beginTime = new Date(begin_timestamp * 1000);//开始时间
        let endTime = new Date(end_timestamp * 1000);//结束时间
        if (date_type == 'DATE_TYPE_FIX_TIME_RANGE') {
          data[i].begin_time = beginTime;
          data[i].end_time = endTime;
        } else if (date_type == 'DATE_TYPE_FIX_TERM') {
          data[i].fixed = 1;
        }

        list.push(data[i]);
      }
    }
  },

  // 加载“待领取”列表
  _load_unclaimed(){
    var that = this;
    
    if(that.data.pageNo == 1){
      wx.showLoading();
    }
    api.request('/card/list', 'GET', {
      'page': that.data.pageNo
    }, (res) => {
      wx.hideLoading();
      var list = that.data.list;
      var data = res.data.data;

      // 调用封装的遍历函数
      that._for_data(data, list);
      that.setData({
        list: list,
        hasMore: res.data.has_more//判断是否有更多
      })
    });
  },

  // 加载“已领取”列表
  _load_received(){
    console.log('刷新列表')
    var that = this;
    if (that.data.pageNo == 1) {
      wx.showLoading();
    }
    api.request('/card/my_list', 'GET', {
      'page': that.data.pageNo
    }, (res) => {
      wx.hideLoading();
      var list = that.data.list;
      var data = res.data.data;
      console.log(data)
      if (data.length) {
        for (var i = 0; i < data.length; i++) {
          list.push(data[i]);
        }
      }
      that.setData({
        list: list,
        hasMore: res.data.has_more//判断是否有更多
      })
    });
  },

  //滚动到底部
  onscrolltolower: function () {
    var that = this;
    that.data.pageNo++;
    if (that.data.hasMore) {
      that._get_couponlist(that.data.activeIndex)
    }
  },

  tabClick: function (e) {
    var that = this;
    let idx = e.currentTarget.dataset.index;
    this.setData({
      activeIndex: idx,
      load_done: false,
      list: [],//清空列表
      pageNo: 1,
      scroll_top: 0,
    })
    if(idx == 1){
      this.setData({
        dlq:false,
        couWidth:'100%'
      })
    }else{
      this.setData({
        dlq:true,
        couWidth: '85%'
      })
    }
    // 加载订单列表
    that._get_couponlist(idx)
 
  },
  // 查看卡券详情
  card_detail(e){
    var that = this
    // 控制点击事件在350ms内触发，加这层判断是为了防止长按时会触发点击事件
    if (that.touchEndTime - that.touchStartTime < 350) {
      // 当前点击的时间
      var currentTime = e.timeStamp
      var lastTapTime = that.lastTapTime
      // 更新最后一次点击时间
      that.lastTapTime = currentTime

      // 如果两次点击时间在300毫秒内，则认为是双击事件
      if (currentTime - lastTapTime < 300) {
        console.log("double tap")
      } else {
        // 单击事件
        that.lastTapTimeoutFunc = setTimeout(function () {
          wx.showLoading()
          let id = e.currentTarget.dataset.id;
          // 已领取，点击查看卡券详情
          let myitem = e.currentTarget.dataset.item;
          let card_id = myitem.card_id;
          let card_code = myitem.decrypt_code;
          let code = myitem.code;
          wx.openCard({
            cardList: [
              {
                cardId: card_id,
                code: card_code
              }
            ],
            success: function (res) {
              console.log(res)
            },
            complete: function () {
              wx.hideLoading()
              // 调用卡券状态同步接口
              api.request('/card/check_code', 'POST', {
                'code': code,
                'decrypt_code': card_code
              }, (res) => {
                // 同步卡券状态后，刷新列表
                that.setData({
                  pageNo:1,
                  list:[]
                })
                that._load_received()
              });
            }
          })
        }, 300);
      }
    }
  },
  //领取卡券
  addCard(e) {
    var that = this;
    wx.showLoading()
    let id = e.currentTarget.dataset.id;
    api.request('/card/card_ext', 'GET', {
      'card_id': id
    }, (res) => {
      console.log(res)
      var cardExt = res.data.cardExt;
      wx.addCard({
        cardList: [
          {
            cardId: id,
            cardExt: cardExt
          }
        ],
        success: function (res) {
          // 保存code，codeId
          res.cardList.forEach(function (item) {
            api.request('/card/save_code', 'POST', {
              'card_id': item.cardId,
              'code': item.code
            }, (res) => {
              console.log(res)
            });
          })
        },
        fail: function (res) {
          console.log(res);
        },
        complete: function () {
          wx.hideLoading()
        }
      })
    });
  },

  // 长按
  longTap: function (e) {
    let code = e.currentTarget.dataset.item.code;
    let decrypt_code = e.currentTarget.dataset.item.decrypt_code;
    console.log(code, '+', decrypt_code)
    var that = this;
    wx.showActionSheet({
      itemList: ['删除'],
      success: function (res) {
        if (!res.cancel) {
          wx.showModal({
            title: '提示',
            content: '是否删除',
            success: function (res) {
              if (res.confirm) {
                // 删除优惠券
                api.request('/card/delete_code', 'POST', {
                  'code':code,
                  'decrypt_code': decrypt_code
                }, (res) => {
                  console.log(res.data)
                  that.setData({
                    pageNo: 1,
                    list: []
                  })
                  that._load_received();
                  wx.showToast({
                    title: '删除成功',
                    icon: 'success',
                    duration: 2500
                  })
                });
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        }
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this._get_couponlist(this.data.activeIndex);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  }
})